package com.wechar_rpa.service;

import com.wechar_rpa.model.UserSubscription;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RenewalReminderService {

    @Autowired
    private UserSubscriptionRepository subscriptionRepository;

    @Autowired
    private WeChatMessageService chatMessageService;

    // 每天凌晨 2:00 执行一次
    @Scheduled(cron = "0 0 2 * * ?")
    public void checkSubscriptionsAndSendReminders() {
        Date tomorrow = new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000);
        List<UserSubscription> subscriptions = subscriptionRepository.findByExpiresAtBefore(tomorrow);

        for (UserSubscription sub : subscriptions) {
            if (sub.getIsActive()) {
                sendRenewalReminder(sub.getUser().getUsername());
            }
        }
    }

    private void sendRenewalReminder(String username) {
        String message = "【WeChat RPA 自动提醒】您的会员订阅即将到期，请及时续费以继续使用白名单回复功能。";
        chatMessageService.saveMessage(new ChatMessage(username, null, message, new Date(), true));
    }
}